package com.wk.springbootlearn.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;

@Component
public class JwtUtils implements InitializingBean {

    public static String SECRET;
    public static int EXPIRA_HOUR;

    @Value("${jwt.signSecret}")
    private String signSecret;
    @Value("${jwt.expirationHour}")
    private int expirationHour;

    @Override
    public void afterPropertiesSet() throws Exception {
        SECRET = this.signSecret;
        EXPIRA_HOUR = this.expirationHour;
    }

    /**
     * 签发token
     * @param userId 用户名
     * @return token字符串
     * @throws UnsupportedEncodingException 生成token失败
     */
    public static String generateToken(String userId) throws UnsupportedEncodingException {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.HOUR, EXPIRA_HOUR);
        Date expireDate = nowTime.getTime();

        return JWT.create()
                .withIssuedAt(new Date())
                .withExpiresAt(expireDate)
                .withClaim("userId", userId)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 校验token合法性
     * @param token
     * @throws UnsupportedEncodingException
     */
    public static void verifyToken(String token) throws UnsupportedEncodingException {
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    // 从token中获取userId
    public static Claim getTokenUserId(String token) {
        return JWT.decode(token).getClaim("userId");
    }

}
